﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CS_BEGINNER_TO_PROFICIENT.STD.DelegatedSTD
{
    public delegate void OrderStatusChangedHandler<T>(T orderStatus);

    public class OrderStatus : EventArgs
    { 
        public string OrderId { get; }
        public string Status { get; }

        public OrderStatus(string orderId, string status)
        {
            OrderId = orderId;
            Status = status;
        }

        public override string ToString() => $"Order Id: {OrderId}, Status: {Status}"; 
    }

    public class Order<T>
    {
        public event OrderStatusChangedHandler<T> StatusChanged;
        private T _orderStatus;

        public Order(T orderStatus) => _orderStatus = orderStatus;

        public void UpdateStatus(T newStatus)
        {
            _orderStatus = newStatus;
            OnStatusChanged(_orderStatus);
        }

        protected virtual void OnStatusChanged(T orderStatus) => StatusChanged?.Invoke(orderStatus);
    }

    public class OrderManagermentSystem
    {
        private readonly List<Order<OrderStatus>> _orders = new List<Order<OrderStatus>>();

        public void Register(Order<OrderStatus> order, OrderStatusChangedHandler<OrderStatus> handler)
        {
            order.StatusChanged += handler;
            _orders.Add(order);
        }

        public void UnRegister(Order<OrderStatus> order, OrderStatusChangedHandler<OrderStatus> handler)
        {
            order.StatusChanged -= handler;
            _orders.Remove(order);
        }
    }

    public class OrderHandler
    {
        public void HandleOrderStatusChanged(OrderStatus orderStatus) => Console.WriteLine($"Order Status Updated: {orderStatus}");
    }

    public class DelegatedSTDP18
    {
        public static void Execute()
        {
            Order<OrderStatus> order1 = new Order<OrderStatus>(new OrderStatus("1", "已送达"));
            Order<OrderStatus> order2 = new Order<OrderStatus>(new OrderStatus("2", "正在配送"));

            OrderManagermentSystem orderManagermentSystem = new OrderManagermentSystem();
            OrderHandler handler = new OrderHandler();

            orderManagermentSystem.Register(order1, handler.HandleOrderStatusChanged);
            orderManagermentSystem.Register(order2, handler.HandleOrderStatusChanged);

            order2.UpdateStatus(new OrderStatus("2", "已送达"));
        }
    }
}